<!DOCTYPE HTML>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link href="../static_pc/assets3/css/bs3/dpl-min.css" rel="stylesheet" type="text/css"/>
    <link href="../static_pc/assets3/css/bs3/bui-min.css" rel="stylesheet" type="text/css"/>
    <!-- <link href="../static_pc/assets/css/dpl-min.css" rel="stylesheet" type="text/css" />
    <link href="../static_pc/assets/css/bui-min.css" rel="stylesheet" type="text/css" /> -->
    <link href="../static_pc/assets/css/page-min.css" rel="stylesheet" type="text/css"/>
    <style>
        /**内容超出 出现滚动条 **/
        .bui-stdmod-body {
            overflow-x: hidden;
            overflow-y: auto;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <form id="searchForm" class="form-horizontal span24">
            <div class="row">
                <div class="control-group span8">
                    <label class="control-label">题目</label>

                    <div class="controls">
                        <input type="text" class="control-text" name="key" placeholder="关键字">
                        <input type="text" name="aaa" style="display: none;">
                    </div>
                </div>
                <div class="span3 offset">
                    <button type="button" id="btnSearch" class="button button-primary">搜索</button>
                </div>
            </div>
        </form>
    </div>
    <div class="search-grid-container">
        <div id="grid"></div>
    </div>
    <div>*正确答案标记为<span style="color: red;">红色</span></div>
</div>


<div id="content" class="hide">
    <form id="J_Form" class="form-horizontal" action="" method="post">
        <input type="hidden" name="id">
        <div class="row">
            <div class="control-group span15">
                <label class="control-label"><s>*</s>题目</label>

                <div class="controls">
                    <input name="title" type="text" data-rules="{required:true}" class="control-text span-width span9">
                </div>
            </div>
        </div>
        <div class="row">
            <div class="control-group span15">
                <label class="control-label"><s>*</s>选项A</label>

                <div class="controls">
                    <input name="ansId" type="hidden">
                    <input name="answer" type="text" data-rules="{required:true}"
                           class="control-text span-width span9">
                    <label><input name="answerradio" type="radio" value="1">设为正确</label>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="control-group span15">
                <label class="control-label"><s>*</s>选项B</label>

                <div class="controls">
                    <input name="ansId" type="hidden">
                    <input name="answer" type="text" data-rules="{required:true}"
                           class="control-text span-width span9">
                    <label><input name="answerradio" type="radio" value="2">设为正确</label>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="control-group span15">
                <label class="control-label"><s>*</s>选项C</label>
                <div class="controls">
                    <input name="ansId" type="hidden">
                    <input name="answer" type="text" data-rules="{required:true}"
                           class="control-text span-width span9">
                    <label><input name="answerradio" type="radio" value="3">设为正确</label>
                </div>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript" src="../static_pc/common/jquery.min-2.1.3.js"></script>
<script type="text/javascript" src="../static_pc/common/JsUtil.js"></script>
<script type="text/javascript" src="../static_pc/layer/layer.js"></script>
<script type="text/javascript" src="../static_pc/assets/js/bui.js"></script>
<script type="text/javascript" src="../static_pc/assets/js/config.js"></script>
<script type="text/javascript">
    BUI.use(['common/search', 'bui/overlay'], function (Search, Grid, Data, overlay) {
        var Mask = BUI.Mask, Overlay = BUI.Overlay,
            Grid = BUI.Grid,
            columns = [
                /*{title: '编号', dataIndex: 'id', elCls: 'center'},*/
                {title: '题目', dataIndex: 'title', elCls: 'center'},
                {
                    title: '答案', dataIndex: '', elCls: 'center', renderer: function (value, obj) {
                    var answers = obj.answers;
                    var answerStr = "";
                    for (var i = 0; i < answers.length; i++) {
                        if (answers[i].id==obj.answerId){
                            answerStr += "<span style='color: red;'>"+answers[i].content + "</span><br>";
                        }else {
                            answerStr += answers[i].content + "<br>";
                        }
                    }
                    return answerStr;
                }
                },
                {title: '发布时间', dataIndex: 'gmtCreate', elCls: 'center'},
            ],
            editing = new Grid.Plugins.DialogEditing({
                contentId: 'content',
                triggerCls: 'btn-edit2',
                editor: {
                    width: 650,
                    title: '编辑(<span style="color: red">正确答案需勾选</span>)',
                    success: function () {
                        var edtor = this,
                            form = edtor.get('form'),
                            editType = editing.get('editType');//add 或者 edit
                        var url = "";
                        var answers = [];
                        if (editType == "add") {
                            $("[name=answer]").each(function(i){
                                answers.push({content:$(this).val()});
                            });
                            url = "../api/ques/saveQues";
                        } else {
                            $("[name=answer]").each(function(i){
                                answers.push({id:$("[name=ansId]").eq(i).val(), content:$(this).val()});
                            });
                            url = "../api/ques/updateQues";
                        }
                        //检验
                        form.valid();
                        if (form.isValid()) {
                            var answerradio = $("input[name='answerradio']:checked").val();
                            layer.load();
                            $.post(url,{id:$("[name=id]").val(),title:$("[name=title]").val(),answersStr:JSON.stringify(answers),right:answerradio},function (data) {
                                layer.closeAll('loading');
                                if (data.hasError) { //返回的数据是 {hasError : fasle,error : 'xxxx',field : 'xxx'},也可以是任意格式的数据如 ： {success : false,'error' : 'xxxxx'}
                                    if (data.errType == "NOAUTH") {
                                        edtor.close();
                                    }
                                    BUI.Message.Alert(data.error, 'warning');
                                } else {
                                    store.load();
                                    edtor.close();
                                    /*BUI.Message.Alert(data.error, function () {
                                        //edtor.close();
                                    }, 'info');*/
                                }
                            },"json").error(function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.closeAll('loading');
                                BUI.Message.Alert("系统繁忙，请稍后" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + textStatus, 'warning');
                            });
                        }
                    }
                }
            }),
            store = Search.createStore('../api/ques/listQuestionByPage', {
                proxy: {
                    save: { //也可以是一个字符串，那么增删改，都会往那么路径提交数据，同时附加参数saveType
                        /* addUrl : '${pageContext.request.contextPath}/admin/addAdm.shtml',
                         updateUrl : '${pageContext.request.contextPath}/admin/updAdm.shtml',
                         removeUrl : '${pageContext.request.contextPath}/admin/delAdm.shtml' */
                    },
                    method: 'POST'
                },
                params: { //配置初始请求的参数
//                        type : type
                },
                pageIndex: 0,
                pageSize: 10,
                autoSync: true //保存数据后，自动更新
            }),
            gridCfg = Search.createGridCfg(columns, {
                forceFit: true,
                emptyDataTpl: '<div class="centered"><img alt="Crying" src="http://img03.taobaocdn.com/tps/i3/T1amCdXhXqXXXXXXXX-60-67.png"><h2>查询的数据不存在</h2></div>',
                tbar: {
                    items: [
                        {text: '<i class="icon-plus"></i>新建', btnCls: 'button button-small', handler: addFunction},
                        {text: '<i class="icon-edit"></i>编辑', btnCls: 'button button-small', handler: updFunction},
                        {text: '<i class="icon-remove"></i>删除', btnCls: 'button button-small', handler: delFunction}
                    ]
                },
                //loadMask: true, //加载数据时显示屏蔽层
                plugins: [editing, BUI.Grid.Plugins.CheckSelection] // 插件形式引入多选表格
            });

        var search = new Search({
                store: store,
                gridCfg: gridCfg
            }),
            grid = search.get('grid');

        editing.on('editorshow',function(ev){
            var type = ev.editType, //add ,edit
                record = editing.get('record');
            //alert(type)
            if(type == 'add'){
                //如果马上保存，通过 ev.editType == 'add' 来判断
                $("input:radio[name=answerradio][value='1']").prop("checked",true);
            }else{
                var answers = record.answers;
                for(var i = 0; i < answers.length; i++){
                    $("[name=ansId]").eq(i).val(answers[i].id);
                    $("[name=answer]").eq(i).val(answers[i].content);
                    if (answers[i].id==record.answerId){
                        var n = i+1;
                        $("input:radio[name=answerradio][value='"+n+"']").prop("checked",true);
                    }
                }
                //alert(JSON.stringify(record));
            }
        });

        function addFunction() {
            var newData = {d: ""}; //标志是新增加的记录
            editing.add(newData, 'data'); //添加记录后，直接编辑
        }

        function updFunction() {
            var selections = grid.getSelection();
            var ids = [];
            BUI.each(selections, function (selections) {
                ids.push(selections.id);
            });

            if (ids.length > 1) {
                BUI.Message.Alert('只能选择一条记录', 'warning');
            } else if (ids.length <= 0) {
                BUI.Message.Alert('请选择要编辑的记录', 'warning');
            } else {
                //alert(JSON.stringify(selections));
                editing.edit(selections[0]);
            }
        }

        //删除操作
        function delFunction() {
            var selections = grid.getSelection();
            //alert(JSON.stringify(selections));
            delItems(selections);
        }

        function delItems(items) {
            var ids = [];
            BUI.each(items, function (item) {
                ids.push(item.id);
            });
            if (ids.length) {
                BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                    layer.load();
                    $.ajax({
                        url: "../api/ques/removeQues",
                        data: {"ids": ids.toString()},
                        dataType: "json",
                        type: "post",
                        async: true,
                        success: function (data) {
                            layer.closeAll('loading');
                            if (!data.hasError) {
                                store.load();
                            } else {
                                BUI.Message.Alert(data.error, 'warning');
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.closeAll('loading');
                            BUI.Message.Alert("系统繁忙，请稍后" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + textStatus, 'warning');
                        }
                    });
                }, 'question');
            } else {
                BUI.Message.Alert("请选择记录", function () {
                }, 'warning');
            }
        }

    });
</script>
</body>
</html>  